<!--
* description: 总部内部领用-内部领用单制作
* author: hzm
* createdDate: 2021-2-23
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="dynamicApiConfigs"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-is-fix-choose="false"
      :dynamic-is-fix-index="false"
      :dynamic-is-show-more-btn="true"
      :callbackObj="callbackObj"
      :dynamic-api-style="'restful'"
    />
    <detail
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData1"
      :popups-visible="editPopupsVisible1"
      :dynamic-api-style="'restful'"
      :numList="numTo"
      @close="closed"
    />
  </div>
</template>

<script>
import { formMixins } from "@/components/mixins/formMixins";
import { oneTableWithViewTemplateMixins } from "@/components/mixins/oneTableWithViewTemplateMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import Vue from "vue";
import { orgApis } from "@/api/paSparePartsManagement";
import { exportExcel } from "@/utils/getTimeString.js";
import request from '@/utils/request'

export default {
  name: "salesSheetMaking",
  components: {
    OneTableTemplate,
    Detail: () => import("./detail"),
  },
  mixins: [oneTableWithViewTemplateMixins, formMixins],
  data() {
    const viewPageCode = this.$route.path;

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode]);
    return {
      numTo : "",
      selectiondata: null,
      moreList: {},
      editPopupsVisible1: false,
      editRowData1: {},
      dynamicApiConfigs: orgApis.queryRequisitionFormProduction,
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
              {
                prop: "controlBtn",
                label: "操作", // 操作
                codeField: "controlBtn",
                width: 100,
                align: "center",
                isComponent: true,
                comps: [
                  {
                    compKey: "propKey1",
                    labelName: "查看",
                    align: "center",
                    codeField: "editControlBtn",
                    clickEvent: (index) => {
                      this.edited(index,'0');
                    },
                    component: () => import("@/components/org/linkButton"),
                  },
                  {
                    compKey: "propKey2",
                    labelName: "编辑",
                    align: "center",
                    codeField: "editControlBtn",
                    clickEvent: (index) => {
                      this.edited(index, "1");
                    },
                    component: () => import("@/components/org/linkButton"),
                  },
                  {
                    compKey: "propKey3",
                    labelName: "作废",
                    align: "center",
                    codeField: "editControlBtn",
                    clickEvent: (index) => {
                      this.$confirm('确定要作废此领用单吗？', '提示').then(_ => {
                        this.edited(index, "2");
                      }).catch(_ => {})
                    },
                    component: () => import("@/components/org/linkButton"),
                  },
                ],
              },
              {
                prop: "requisitionCode",
                label: "领用单号",
                align: "center",
              },
              {
                prop: "warehouseName",
                label: "领用仓库",
                align: "center",
              },
              {
                prop: "deptName",
                label: "领用部门",
                align: "center",
              },
              {
                prop: "budgetNumber",
                label: "预算号",
                align: "center",
              },
              {
                prop: "empName",
                label: "领用人",
                align: "center",
              },
              {
                prop: "requisitionVariety",
                label: "品种数",
                align: "center",
              },
              {
                prop: "requisitionUse",
                label: "领用用途",
                align: "center",
              },
              {
                prop: "receiver",
                label: "收货人",
                align: "center",
              },
              {
                prop: "receiverPhone",
                label: "联系电话",
                align: "center",
              },
              {
                prop: "requisitionStatusCn",
                label: "单据状态",
                align: "center",
              },
              {
                prop: "receiverAddress",
                label: "收货地址",
                align: "center",
              },
            ],
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
              .tableComponents
          : [
              // 库存状态
              {
                compKey: "compKey1",
                labelName: "领用单号：",
                codeField: "requisitionCode",
                component: () => import("@/components/org/commonInput"),
                oFields: "AsId,AsText",
                type: "inputText",
                isMust: true,
                span: 6,
              },
              // 车辆状态
              {
                compKey: "compKey2",
                labelName: "领用仓库：",
                codeField: "warehouseId",
                customObj: {
                  api: orgApis.queryCK,
                  defOptionFields:['warehouseId','warehouseName']
                },
                component: () => import("@/components/org/commonSelect"),
                type: "dropdownList",
                isMust: true,
                span: 6,
              },
              // 入库仓库
              {
                compKey: "compKey3",
                labelName: "领用部门：",
                codeField: "deptName",
                component: () => import("@/components/org/commonInput"),
                oFields: "AsId,AsText",
                type: "inputText",
                isMust: true,
                span: 6,
              },
              // 审核状态
              {
                compKey: "compKey4",
                labelName: "领用人：",
                codeField: "empName",
                component: () => import("@/components/org/commonInput"),
                oFields: "AsId,AsText",
                type: "inputText",
                isMust: true,
                span: 6,
              },
              {
                compKey: "compKey5",
                labelName: "单据状态：",
                codeField: "lookupValueCode",
                // customObj: {
                //   api: orgApis.queryDropDown1,
                //   defOptionFields:['lookupValueCode','lookupValueName']
                // },
                // component: () => import("@/components/org/commonSelect"),
                component: () => import('@/components/wms/dropdownList/dropdownList'),
                options: [],
                type: "dropdownList",
                isMust: false,
                span: 6,
              },
            ],
      tableButtons: [
        {
          conmpKey: "btenKey1",
          type: "primary",
          size: "small",
          text: "查询",
          name: 'search',
          clickEvent: () => this.queryTable(1),
          position: "right",
        },
        {
          conmpKey: "btenKey2",
          type: "",
          size: "small",
          text: "新增",
          icon: 'el-icon-circle-plus-outline',
          clickEvent: (index) => this.edited(index,'3'),
          position: "left",
        },
        {
          conmpKey: "btenKey3",
          type: "",
          size: "small",
          text: "导出",
          icon: 'el-icon-upload2',
          name: "export",
          clickEvent: () => this.exportExcel1(),
          position: "left",
        },
        {
          conmpKey: "btenKey4",
          type: "",
          size: "small",
          text: "重置",
          name: "reset",
          clickEvent: () => this.reset(),
          position: "right",
        },
        {
          conmpKey: "btenKey5",
          type: "primary",
          size: "small",
          text: "提交",
          icon: 'el-icon-circle-check',
          clickEvent: () => this.submitOrder(),
          position: "left",
        },
      ],
      formField: this.$utils.getFormField(
        this,
        {
          requisitionCode: "",
          warehouseId: "",
          deptName: "",
          empName: "",
          lookupValueCode: "",
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      callbackObj: {
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelect: (selection, row) => {
          this.selectiondata = selection;
        },
      },
    };
  },
  methods: {
    exportExcel1() {
      //导出
      exportExcel(
        this.formField,
        orgApis.exportRequisitionFormProduction.APIUrl,
        orgApis.exportRequisitionFormProduction.ServiceCode,
        "内部领用单制作"
      );
    },
    // 编辑弹窗
    edited(index, num) {
      let that = this
      // this.numTo = num
      this.editRowData1 = this.$refs["multipleTable"].list[index]
      if (num == "2") {
        let queryObj = {
          apiConfig: orgApis.modifyStatus,
          //条件/实体参数（变量），根据typeParam中的定义配置
          variables: this.editRowData1
        };
        //转换了中台请求格式数据
        var paramD = that.$getParams(queryObj);
        // 调用中台API方法（可复用）
        that.$requestAPI(paramD).then((response) => {
          if (response.result === "0") {
            return;
          }
          var getResult = response;
          if (getResult.result === "1") {
            that.$message({
              message: "作废成功",
              type: "success",
              duration: 2000,
            });
            that.queryTable(1);
            // 重置表单
            // that.resetRight(tableRef)
            // 重新加载
            // that.onLeftRowClick(null);
          } else {
            that.$message({
              message: getResult.msg,
              type: "warning",
              duration: 2000,
            });
          }
        });
      } else if (num == "1") {
        this.numTo='edit'
        this.editPopupsVisible1 = true
      } else if (num == '3') {
        this.numTo='add'
        this.editPopupsVisible1 = true
      } else if (num == '0') {
        this.numTo='eye'
        this.editPopupsVisible1 = true
      }
    },
    closed(type) {
      this.editPopupsVisible1 = type;
    },
    // 提交
    submitOrder() {
      let that = this;
      let infoQue = { list: [] };
      this.selectiondata.forEach(function (val, index) {
        infoQue.list.push({
          updateControlId: val.updateControlId,
          requisitionId: val.requisitionId,
          updateControlId: val.updateControlId,
        });
      });
      let queryObj = {
        apiConfig: orgApis.submit,
        //条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          //当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: infoQue,
        },
      };
      //转换了中台请求格式数据
      var paramD = that.$getParams(queryObj);
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === "0") {
          return;
        }
        var getResult = response;
        if (getResult.result === "1") {
          that.$message({
            message: "提交成功",
            type: "success",
            duration: 2000,
          });
          that.queryTable(1);
          // 重置表单
          // that.resetRight(tableRef)
          // 重新加载
          // that.onLeftRowClick(null);
        } else {
          that.$message({
            message: getResult.msg,
            type: "warning",
            duration: 2000,
          });
        }
      });
    },
    //单据状态
    getDocumentStatus(){
      request({
        url: orgApis.queryDropDown1.APIUrl,
        method: 'post',
        data: {}
      }).then((res) => {
        console.log("res:",res)
        for(let i=0;i<res.rows.length;i++){
          if(res.rows[i].lookupValueName!=='已作废' && res.rows[i].lookupValueName!=='已审核' && res.rows[i].lookupValueName!=='已提交'){
            this.tableComponents.find(o=>o.codeField==='lookupValueCode').options.push({
              label: res.rows[i].lookupValueName,
              value: res.rows[i].lookupValueCode
            })
          }
        }
        // res.rows.map((item) => {
        //   this.tableComponents[0].options.push({
        //     label: item.opratePartName,
        //     value: item.operatePartCode
        //   })
        // })
      })
    }
  },
  mounted() {
    //获取单据状态
    this.getDocumentStatus()
    // this.queryTable(1)
    // this.$refs.multipleTable.list = [
    //   {
    //     index: 1,
    //   },
    // ]
  },
};
</script>

<style>
</style>
